package com.qiu.greened.ui.start

import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.content.edit
import androidx.lifecycle.lifecycleScope
import com.qiu.greened.MainActivity
import com.qiu.greened.bean.UserPostBean
import com.qiu.greened.databinding.ActivitySplashBinding
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.ui.my.LoginActivity
import com.qiu.greened.ui.my.RegisterActivity
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.launch

class SplashActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySplashBinding
    private lateinit var save: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
        save = getSharedPreferences("data", MODE_PRIVATE)
        val phone = save.getString("phone", "").toString()
        if (phone != "") {
            val password = save.getString("password", "").toString()
            login(phone, password)
        } else {
            binding.motionLayout.post {
                Thread.sleep(500)
                binding.motionLayout.transitionToEnd()
            }
        }
        binding.btnLogin.setOnClickListener {
            startActivity(Intent(this, LoginActivity::class.java))
        }
        binding.btnRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }

    }

    private fun login(phone: String, password: String) {
        lifecycleScope.launch {
            try {
                val data = ServiceCreator.create<UserService>()
                    .getUserLoginData(UserPostBean(phone, password)).dataConvert()
                save.edit {
                    putString("userName", data.userName)
                    putString("userAvatar", data.userAvatar)
                    putString("token", data.token)
                }
                MyData.setLoginData()
                "登录成功".showToast()
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                finish()
            } catch (e: Exception) {
                e.printStackTrace()
                "请求失败 ==> ${e.message}".showToast()
                Log.i("请求失败", "${e.message}")
                binding.motionLayout.post {
                    binding.motionLayout.transitionToEnd()
                }
            }
        }
    }
}